<?php

/**
 * 股票买入交易账目
 *
 * @package		Hooloo framework
 * @author 		Bill
 * @copyright 	Hooloo Co.,Ltd
 * @version		1.0
 * @release		2017.05.08
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Stock extends Controller{
	public function __construct(){
		parent::__construct();
	}
	
	/**
     * 用户持仓
     */
	public function bull($demo_account = 0, $bull_type = 0, $start_time = 0, $end_time = 0, $username = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		$where = " where a.aid = $aid and can_sell = 1";
		
		//帐号类型
		if($demo_account == 0){
			$where .= " and b.demo_account = 0";
		} elseif($demo_account == 1){
			$where .= " and b.demo_account = 1";
		} else{
			$demo_account = 2;
		}
		
		//融资类型
		if ($bull_type == 1) {
			$where .= " and a.bull_type = 1";
		} elseif ($bull_type == 2) {
			$where .= " and a.bull_type = 2";
		}
		
		//股票代码
		// if ($stock_code) {
			// $stype = substr($stock_code, 0, 2);
			// $scode = substr($stock_code, 2);
			// $where .= " and (a.stock_code = '$scode' and a.stock_type = '$stype')";
		// }
		
		//搜索时间
		if ($start_time && $end_time) {
			$start = strtotime($start_time);
			$end = strtotime($end_time . " 23:59:59");
			$where .= " and a.bull_time >= '$start' and a.bull_time <= '$end'";
		} elseif ($start_time) {
			$start = strtotime($start_time);
			$where .= " and a.bull_time >= '$start'";
			$end_time = 0;
		} elseif ($end_time) {
			$end = strtotime($end_time . " 23:59:59");
			$where .= " and a.bull_time <= '$end'";
			$start_time = 0;
		}
		//搜索条件
		$username = urldecode($username);
		if($username){
			$where .= " and (a.username like '%$username%' or a.stock_code = '$username' or a.stock_name = '$username')";
		} else{
			$username = 0;
		}
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始

		//查询总数
		$sql = "select count(*) as c from stock_bull a inner join user b on a.uid = b.id " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//分页查询
		$sql = "select a.*, a.id bull_id, concat(a.stock_type, a.stock_code) as stock, b.demo_account, b.agent_name, b.id uid from stock_bull a inner join user b on a.uid = b.id " . $where . " order by a.id desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/" . $demo_account . "/" . $bull_type . "/". $start_time . "/". $end_time . "/". $username . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//查询所有代理商
		$sql = "select * from agent";
		$agent = $this->db->query($sql)->result_array();
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		
		$this->assign("demo_account", $demo_account);
		$this->assign("bull_type", $bull_type);
		$this->assign("start_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("username", $username);
		$this->display();
	}
	
	/**
     * 用户平仓
     */
	public function sell($demo_account = 0, $sell_type = 0, $start_time = 0, $end_time = 0, $username = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		$where = " where a.aid = $aid";
		
		//帐号类型
		if($demo_account == 0){
			$where .= " and b.demo_account = 0";
		} elseif($demo_account == 1){
			$where .= " and b.demo_account = 1";
		} else{
			$demo_account = 2;
		}
		
		//融资类型
		if ($sell_type == 1) {
			$where .= " and a.sell_type = 1";
		} elseif ($sell_type == 2) {
			$where .= " and a.sell_type = 2";
		}

		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d");
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		$where .= " and a.sell_time >= '".strtotime($start_time)."' and a.sell_time <= '".strtotime($end_time . " 23:59:59")."'";
		
		//搜索条件
		$username = urldecode($username);
		if($username){
			$where .= " and (a.username like '%$username%' or a.stock_code = '$username' or a.stock_name = '$username')";
		} else{
			$username = 0;
		}
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始
		
		//查询总数
		$sql = "select count(*) as c from stock_sell a inner join user b on a.uid = b.id inner join stock_bull c on c.id = a.bull_id " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//分页查询
		$sql = "select a.*, concat(a.stock_type, a.stock_code) as stock, b.demo_account, b.agent_name, b.id uid from stock_sell a inner join user b on a.uid = b.id inner join stock_bull c on c.id = a.bull_id " . $where . " order by id desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();

		//计算盈亏
		foreach ($list as $key => $val) {
			$list[$key]["cost"] = $val['cost_money'] + round(round($val['bull_price'] * $val["sell_num"], 2) * 0.003, 2);//手续费：买入手续费 + 卖出手续费
			//盈亏：卖出后收益 - 手续费 - 留仓费 - 印花税 - 管理费
			$list[$key]["total_gain"] = round($val["gain"] - $list[$key]["cost"] - $val["save_money"] - $val["stamp_money"] - $val["manage_money"], 2);
		}
		
		//平仓手续费总和，留仓费总和，平仓盈亏合计
		$sql = "select sum(a.gain) gain,  sum(round(((a.sell_num * a.bull_price) * 0.003), 2) + a.cost_money) cost, sum(a.save_money + a.stamp_money + a.manage_money) save_money from stock_sell a inner join user b on a.uid = b.id inner join stock_bull c on c.id = a.bull_id " . $where;
		$count = $this->db->query($sql)->row_array();
		$count["total_gain"] = $count["gain"] - $count["cost"] - $count["save_money"];
		
		//分页展示
		$url = "/" . $this->_controller . '/' . $this->_action . '/' . $demo_account . "/" . $sell_type . "/". $start_time . "/". $end_time . "/". $username . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		$this->assign("count", $count);
		
		$this->assign("demo_account", $demo_account);
		$this->assign("bull_type", $sell_type);
		$this->assign("start_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("username", $username);
		$this->display();
	}
	
	/**
     * 用户委托
     */
	public function trust($demo_account = 0, $status = 3, $start_time = 0, $end_time = 0, $username = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		$where = " where a.aid = $aid";

		//帐号类型
		if ($demo_account == 0 || $demo_account == 1) {
			$where .= " and b.demo_account = $demo_account";
		} else{
			$demo_account = 2;
		}
		
		//委托状态
		if ($status >= 0 && $status < 3) {
			$where .= " and a.status = $status";
		} else {
			$status = 3;
		}

		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d");
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		$where .= " and a.stock_trust_time >= '".strtotime($start_time)."' and a.stock_trust_time <= '".strtotime($end_time . " 23:59:59")."'";
		
		//搜索条件
		if($username){
			$where .= " and (a.username like '%$username%')";
		} else{
			$username = 0;
		}
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始
		
		//查询总数
		$sql = "select count(*) as c from stock_trust a inner join user b on a.uid = b.id " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//分页查询
		$sql = "select a.*, concat(a.stock_type, a.stock_code) as stock, b.demo_account, b.agent_name, b.id uid, 0.00 new_price from stock_trust a inner join user b on a.uid = b.id " . $where . " order by a.id desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//获取股票
		$count = 0;
		if ($list) {
			$stock = array_column($list, "stock");
			$stock = array_unique($stock);
			$stock_info = get_stock($stock);

			//当前价格
			foreach ($list as $key => $val) {
				if ($val["status"] < 1) {
					$count += $val["money"];
					$list[$key]["new_price"] = round($stock_info[$val["stock"]][3], 2);//当前价格
				} else {
					$list[$key]["new_price"] = "--";
				}
			}
			$count = round($count, 2);
		}
		
		//分页展示
		$url = "/" . $this->_controller . '/' . $this->_action . '/' . $demo_account . "/" . $status . "/". $start_time . "/". $end_time . "/". $username . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		$this->assign("count", $count);
		
		$this->assign("demo_account", $demo_account);
		$this->assign("status", $status);
		$this->assign("start_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("username", $username);
		$this->display();

		$this->display();
	}
	
	/**
     * 盈亏排序
     */
	public function gain($sort = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		
		//查询持仓
		if ($sort == 2) {
			//日盈亏
			$start = strtotime(date("Y-m-d 09:00:00"));
			$end = time();
			$where = "where a.sell_time >= $start and a.sell_time <= $end and a.aid = $aid";
		} elseif ($sort == 1) {
			//周盈亏
			$start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'))));
			$end = time();
			$where = "where a.sell_time >= $start and a.sell_time <= $end and a.aid = $aid";
		} else {
			//总盈亏
			$where = "where a.aid = $aid";
		}
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始
		
		//查询总数
		$sql = "select count(*) as c from (SELECT (sum(a.gain) - sum(a.cost_money+a.save_money+a.manage_money+b.bull_cost_money+a.stamp_money)) total_gain, a.username, a.uid, c.agent_name, c.realname FROM `stock_sell` a INNER JOIN stock_bull b on a.bull_id = b.id INNER JOIN `user` c on c.id = a.uid " . $where . " GROUP BY a.uid ORDER BY total_gain) as t";
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//分页查询
		$sql = "SELECT (sum(a.gain) - sum(a.cost_money+a.save_money+a.manage_money+b.bull_cost_money+a.stamp_money)) total_gain, a.username, a.uid, c.agent_name, c.realname FROM `stock_sell` a INNER JOIN stock_bull b on a.bull_id = b.id INNER JOIN `user` c on c.id = a.uid " . $where . " GROUP BY a.uid ORDER BY total_gain DESC limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//分页展示
		$url = "/" . $this->_controller . '/' . $this->_action . '/' . $sort . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		
		$this->assign("sort", $sort);
		$this->display();
	}
	
	/**
     * 融资/融券持仓统计
     */
	public function hold($bull_type = 0, $sear = 0, $p = 1){
		//指定代理商
		$aid = $_SESSION["agent"]["id"];
		
		//查询持仓
		$where = " where can_sell = 1 and aid = $aid";

		//股票类型
		if ($bull_type == 1 || $bull_type == 2) {
			$where .= " and bull_type = $bull_type";
		}
		
		//搜索条件
		if($sear){
			$where .= " and (stock_code like '%$sear%' or stock_name like '%$sear%')";
		} else{
			$sear = 0;
		}
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始
		
		//查询总数
		$sql = "select count(*) as c from (SELECT stock_code FROM stock_bull " . $where . " GROUP BY stock_code) as t";
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//分页查询
		$sql = "select stock_code, stock_name, concat(stock_type, stock_code) as stock, sum(bull_num - sell_num) as num, avg(bull_price) as avg_price, sum(bull_money) as bull_money from stock_bull " . $where . " GROUP BY stock_code order by stock_code desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//股票信息
		$stock = array_column($list, "stock");
		$stock = array_unique($stock);
		$stock_info = get_stock($stock);

		//计算涨幅
		foreach ($list as $key => $val) {
			$price = round($stock_info[$val["stock"]][3], 2);//当前价格
			if ($price != 0) {
				if ($bull_type == 1) {
					$zf = ($price - $val["avg_price"]) / $price * 100;
				} else {
					$zf = ($val["avg_price"] - $price) / $price * 100;
				}
			} else {
				$zf = 0;
			}
			$list[$key]["zf"] = round($zf, 2);
			$list[$key]["price"] = $price;
		}
		
		//分页展示
		$url = "/" . $this->_controller . '/' . $this->_action . '/' . $bull_type . "/". $sear . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//分配展示
		$this->assign("list", $list);
		$this->assign("page", $page);
		$this->assign("total", $total);
		
		$this->assign("bull_type", $bull_type);
		$this->assign("sear", $sear);
		$this->display();
	}
	
	/**
     * 强制平仓
     */
	public function ajax_set_sell() {
		if (IS_POST) {
			//接收参数
			$id = isset($_POST["id"]) ? (int)$_POST["id"] : 0;
			$num = isset($_POST["id"]) ? (int)$_POST["num"] : 0;

			//卖出股票（强制）
			$result = sell_stock($id, $num, 0, 1);

			//返回卖出
			ajax_return($result["status"], $result["msg"]);
		}
	}

	/**
     * 撤销委托单
     */
	public function ajax_set_trust() {
		if (IS_POST) {
			//接收参数
			$id = isset($_POST["id"]) ? (int)$_POST["id"] : 0;
			$trust_type = isset($_POST["trust_type"]) ? (int)$_POST["trust_type"] : 0;
			
			//执行操作
			$result = common_trust($id, $trust_type);
			
			//返回卖出
			ajax_return($result["status"], $result["msg"]);
		}
	}
	
	/**
     * 持仓单-最新价格
     */
	public function ajax_get_bull() {
		if (IS_AJAX) {
			//接收参数
			$aid = $_SESSION["agent"]["id"];
			$bull_id = isset($_POST["data"]) ? trim(sql_format($_POST["data"]), ",") : "";
			$aid = $_SESSION["agent"]["id"];
			$result = array();
			
			//校验参数
			if ($bull_id) {
				//查询记录
				$sql = "select id bull_id, aid, uid, username, stock_type, stock_code, stock_name, can_sell_num, bull_type, bull_price, bull_time, bull_num, sell_num, bull_cost_money, concat(stock_type, stock_code) as code from `stock_bull` where id in ($bull_id) and aid = $aid";
				$list = $this->db->query($sql)->result_array();
				
				//判断记录是否存在
				if ($list) {
					//股票行情
					$stock_info = array_column($list, "code");
					$stock_info = get_stock($stock_info);

					//计算浮盈
					foreach ($list as $key => $val) {
						//股票最新价格，如果停盘交易价格按照昨天收盘价格收盘
						$sell_price = round($stock_info[$val["code"]][3], 2);
						if ($sell_price <= 0) {
							$sell_price = round($stock_info[$val["code"]][2], 2);
							$disable = 1;
						} else {
							$disable = 0;
						}
						
						//设置参数
						$data["price"] = $sell_price;//卖出价格
						$data["num"] = $val["bull_num"] - $val["sell_num"];//卖出数量（考虑委托）
						$data["bull_type"] = $val["bull_type"];//股票类型1-融资，2-融券
						$data["bull_price"] = $val["bull_price"];//买入价格
						$data["stock_code"] = $val["stock_code"];//股票代码
						$data["bull_time"] = $val["bull_time"];//建仓时间
						
						//计算卖出
						$sell = common_sell($data);
	
						//组装参数
						$result[$val["bull_id"]]["price"] = number_format($sell_price, 2);//当前价格
						$result[$val["bull_id"]]["save"] = number_format($sell["save_money"], 2) . "/" . $sell["save_day"] . "天";
						$result[$val["bull_id"]]["total_gain"] = $sell["total_gain"];//浮动盈亏
						$result[$val["bull_id"]]["manage_money"] = number_format($sell["manage_money"], 2);//管理费金额
						$result[$val["bull_id"]]["can_sell"] = $disable;//是否可以卖
						$result[$val["bull_id"]]["bull_money"] = round($data["num"] * $val["bull_price"], 2);//持仓金额
					}
				}
			}
			//返回结果
			ajax_return(1, "SUCCESS", $result);
		}
	}

	/**
     * 委托单-最新价格
     */
	public function ajax_get_trust() {
		if (IS_AJAX) {
			//接收参数
			$aid = $_SESSION["agent"]["id"];
			$trust_id = isset($_POST["data"]) ? trim(sql_format($_POST["data"]), ",") : "";
			$result = array();
			
			//校验参数
			if ($trust_id) {
				//查询记录
				$sql = "select id, stock_code, status, stock_type, stock_deal_time, CONCAT(stock_type, stock_code) as code from stock_trust where id in ($trust_id) and aid = $aid";
				$list = $this->db->query($sql)->result_array();
				
				//判断记录是否存在
				if ($list) {
					//股票行情
					$stock_info = array_column($list, "code");
					$stock_info = get_stock($stock_info);
					
					//计算浮盈
					foreach ($list as $key => $val) {
						$result[$val["id"]]["status"] = $val["status"];
						if (round($stock_info[$val["code"]][3], 2) > 0) {
							$result[$val["id"]]["price"] = number_format($stock_info[$val["code"]][3], 2);
							$result[$val["id"]]["stock_deal_time"] = $val["stock_deal_time"] == 0 ? "--" : date("Y-m-d H:i:s", $val["stock_deal_time"]);
						} else {
							$result[$val["id"]]["price"] = "--";
							$result[$val["id"]]["stock_deal_time"] = $val["stock_deal_time"] == 0 ? "--" : date("Y-m-d H:i:s", $val["stock_deal_time"]);
						}
					}
				}
			}
			
			//返回结果
			ajax_return(1, "SUCCESS", $result);
		}
	}
}
